from controllers.Base import HttpController, g_messageCmdXcmsStreamList, g_messageCmdXcmsLiveStart, \
    g_messageCmdXcmsLiveStop, g_xcmsDict, g_xcnvsMediaApi, g_logger, g_settings, g_messageCmdXcmsRecordTimeline, \
    g_messageCmdXcmsRecordFilename, g_messageCmdXcmsStreamAddProxy, g_messageCmdXcmsStreamDelProxy, \
    g_messageCmdXcmsStreamPtz
import json
from settings import g_settings


class XcnvsMessageController(HttpController):
    async def get(self, *args, **kwargs):
        data = await self.do()
        self.write(data)

    async def do(self):
        ret = False
        msg = "unknown error"
        message = {}

        request_params = self.request_get_params()
        safe = request_params.get('safe',"").strip()
        if safe == g_settings.appKey + g_settings.appSecret:
            message_type = request_params.get('message_type',"").strip()
            message_uuid = request_params.get('message_uuid', "").strip()
            is_del = True if int(request_params.get('is_del', 1)) == 1 else False

            if message_type == "CmdXcmsStreamList":
                message = g_messageCmdXcmsStreamList.get(message_uuid)
                if not message:
                    message = {}
                    msg = "this message does not exist"
                else:
                    if is_del:
                        try:
                            del g_messageCmdXcmsStreamList[message_uuid]
                        except Exception as e:
                            g_logger.error("del message_uuid=%s error: %s" % (message_uuid, str(e)))
                    ret = True
                    msg = "success"
            elif message_type == "CmdXcmsLiveStart":
                message = g_messageCmdXcmsLiveStart.get(message_uuid)
                if not message:
                    message = {}
                    msg = "this message does not exist"
                else:
                    if is_del:
                        try:
                            del g_messageCmdXcmsLiveStart[message_uuid]
                        except Exception as e:
                            g_logger.error("del message_uuid=%s error: %s" % (message_uuid, str(e)))

                    ret = True
                    msg = "success"
            elif message_type == "CmdXcmsLiveStop":
                message = g_messageCmdXcmsLiveStop.get(message_uuid)
                if not message:
                    message = {}
                    msg = "this message does not exist"
                else:
                    if is_del:
                        try:
                            del g_messageCmdXcmsLiveStop[message_uuid]
                        except Exception as e:
                            g_logger.error("del message_uuid=%s error: %s" % (message_uuid, str(e)))

                    ret = True
                    msg = "success"
            elif message_type == "CmdXcmsRecordTimeline":
                message = g_messageCmdXcmsRecordTimeline.get(message_uuid)
                if not message:
                    message = {}
                    msg = "this message does not exist"
                else:
                    if is_del:
                        try:
                            del g_messageCmdXcmsRecordTimeline[message_uuid]
                        except Exception as e:
                            g_logger.error("del message_uuid=%s error: %s" % (message_uuid, str(e)))

                    ret = True
                    msg = "success"
            elif message_type == "CmdXcmsRecordFilename":
                message = g_messageCmdXcmsRecordFilename.get(message_uuid)
                if not message:
                    message = {}
                    msg = "this message does not exist"
                else:
                    if is_del:
                        try:
                            del g_messageCmdXcmsRecordFilename[message_uuid]
                        except Exception as e:
                            g_logger.error("del message_uuid=%s error: %s" % (message_uuid, str(e)))

                    ret = True
                    msg = "success"
            elif message_type == "CmdXcmsStreamAddProxy":
                message = g_messageCmdXcmsStreamAddProxy.get(message_uuid)
                if not message:
                    message = {}
                    msg = "this message does not exist"
                else:
                    if is_del:
                        try:
                            del g_messageCmdXcmsStreamAddProxy[message_uuid]
                        except Exception as e:
                            g_logger.error("del message_uuid=%s error: %s" % (message_uuid, str(e)))

                    ret = True
                    msg = "success"
            elif message_type == "CmdXcmsStreamDelProxy":
                message = g_messageCmdXcmsStreamDelProxy.get(message_uuid)
                if not message:
                    message = {}
                    msg = "this message does not exist"
                else:
                    if is_del:
                        try:
                            del g_messageCmdXcmsStreamDelProxy[message_uuid]
                        except Exception as e:
                            g_logger.error("del message_uuid=%s error: %s" % (message_uuid, str(e)))

                    ret = True
                    msg = "success"
            elif message_type == "CmdXcmsStreamPtz":
                message = g_messageCmdXcmsStreamPtz.get(message_uuid)
                if not message:
                    message = {}
                    msg = "this message does not exist"
                else:
                    if is_del:
                        try:
                            del g_messageCmdXcmsStreamPtz[message_uuid]
                        except Exception as e:
                            g_logger.error("del message_uuid=%s error: %s" % (message_uuid, str(e)))

                    ret = True
                    msg = "success"
            else:
                msg = "unsupported message type:%s"%message_type
        else:
            msg = "unsafe"

        res = {
            "code": 1000 if ret else 0,
            "msg": msg,
            "message": message
        }

        return json.dumps(res)
        # return json.dumps(data, cls=ComplexEncoder)

class XcnvsDevCacheController(HttpController):
    async def get(self, *args, **kwargs):
        data = await self.do()
        self.write(data)

    async def do(self):
        ret = False
        msg = "unknown error"
        info = {}
        request_params = self.request_get_params()
        safe = request_params.get('safe',"").strip()
        if safe == g_settings.appKey + g_settings.appSecret:
            info["xcmsDictCount"] = len(g_xcmsDict)
            xcmsDict = {}
            for k,v in g_xcmsDict.items():
                xcmsDict[k] = {
                    "timestamp":v["timestamp"],
                    "date":v["date"],
                    "xcms_name":v["xcms_name"],
                    "xcms_describe":v["xcms_describe"],
                    "xcms_version":v["xcms_version"],
                    "xcms_flag":v["xcms_flag"],
                    "xcms_systemName":v["xcms_systemName"]
                }

            info["xcmsDict"] = xcmsDict
            info["CmdXcmsStreamListCount"] = len(g_messageCmdXcmsStreamList)
            info["CmdXcmsStreamList"] = g_messageCmdXcmsStreamList
            info["CmdXcmsLiveStartCount"] = len(g_messageCmdXcmsLiveStart)
            info["CmdXcmsLiveStart"] = g_messageCmdXcmsLiveStart
            info["CmdXcmsLiveStopCount"] = len(g_messageCmdXcmsLiveStop)
            info["CmdXcmsLiveStop"] = g_messageCmdXcmsLiveStop

            info["CmdXcmsRecordTimelineCount"] = len(g_messageCmdXcmsRecordTimeline)
            info["CmdXcmsRecordTimeline"] = g_messageCmdXcmsRecordTimeline

            info["CmdXcmsRecordFilenameCount"] = len(g_messageCmdXcmsRecordFilename)
            info["CmdXcmsRecordFilename"] = g_messageCmdXcmsRecordFilename

            info["CmdXcmsStreamAddProxyCount"] = len(g_messageCmdXcmsStreamAddProxy)
            info["CmdXcmsStreamAddProxy"] = g_messageCmdXcmsStreamAddProxy

            info["CmdXcmsStreamDelProxyCount"] = len(g_messageCmdXcmsStreamDelProxy)
            info["CmdXcmsStreamDelProxy"] = g_messageCmdXcmsStreamDelProxy

            info["CmdXcmsStreamPtzCount"] = len(g_messageCmdXcmsStreamPtz)
            info["CmdXcmsStreamPtz"] = g_messageCmdXcmsStreamPtz

            ret = True
            msg = "success"
        else:
            msg = "unsafe"

        res = {
            "code": 1000 if ret else 0,
            "msg": msg,
            "info": info
        }

        return json.dumps(res)
        # return json.dumps(data, cls=ComplexEncoder)

# 查看nvs的所有在线直播流
class XcnvsDevMediaListController(HttpController):
    async def get(self, *args, **kwargs):
        data = await self.do()
        self.write(data)

    async def do(self):
        ret = False
        msg = "unknown error"
        data = []
        request_params = self.request_get_params()
        safe = request_params.get('safe',"").strip()
        if safe == g_settings.appKey + g_settings.appSecret:
            data = g_xcnvsMediaApi.getMediaList()
            ret = True
            msg = "success"
        else:
            msg = "unsafe"

        res = {
            "code": 1000 if ret else 0,
            "msg": msg,
            "data": data
        }
        return json.dumps(res)
# 关闭nvs的在线直播流
class XcnvsCloseStreamsController(HttpController):
    async def get(self, *args, **kwargs):
        data = await self.do()
        self.write(data)

    async def do(self):
        ret = False
        msg = "unknown error"
        count_hit = 0
        count_closed = 0
        request_params = self.request_get_params()
        safe = request_params.get('safe',"").strip()
        if safe == g_settings.appKey + g_settings.appSecret:
            app = request_params.get('app',"").strip()
            name = request_params.get('name',"").strip()
            force = int(request_params.get('force',1))

            count_hit, count_closed, msg = g_xcnvsMediaApi.close_streams(app,name,force=force)
            ret = True
        else:
            msg = "unsafe"

        res = {
            "code": 1000 if ret else 0,
            "msg": msg,
            "count_hit": count_hit,
            "count_closed": count_closed,
        }
        return json.dumps(res)
